package com.example.myapplication.base.network.rxJava;




import com.example.myapplication.base.ApiException;
import com.example.myapplication.base.DataResult;

import com.harmonyos.rxharmony.schedulers.HarmonySchedulers;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;

import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Response;

/**
 * RxJava 的工具类
 * <p>
 */

public final class RxUtil {

    private RxUtil() {
    }

    /**
     * 线程切换处理，io线程发布，main线程订阅
     *
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<T, T> transSchedule() {
        return tObservable -> tObservable.subscribeOn(Schedulers.io())
                .observeOn(HarmonySchedulers.mainThread());
    }

    /**
     * 请求结果预处理，根据DataResult的情况做具体处理
     *
     * @param <T>
     * @return
     */

    public static <T> ObservableTransformer<DataResult<T>, T> transData() {
        return dataResultObservable -> dataResultObservable.flatMap((Function<DataResult<T>, ObservableSource<T>>) result -> {
            if (result.getCode() == 0) {
                return Observable.just(result.getData());
            }
            return Observable.error(new ApiException(result.getMsg(), -1));
        });
    }

    public static <T> ObservableTransformer<Response<DataResult<T>>, T> transResponseData() {
        return dataResultObservable -> dataResultObservable.flatMap((Function<Response<DataResult<T>>, ObservableSource<T>>) result -> {
            if (result != null && result.body() != null &&(result.body().getCode() == 200)) {
                return Observable.just(result.body().getData());
            }
            if (result == null)
                return Observable.error(new ApiException("no result", -1));
            if(result !=null&&result.body()==null){
                if(result.message()==null||result.message().isEmpty()){
                    return Observable.error(new ApiException("Error code:"+result.code(),result.code()));
                }
                return Observable.error(new ApiException(result.message(),result.code()));
            }
            return Observable.error(new ApiException(result.body().getMsg(), -1));
        });
    }

    /**
     * 同时做网络请求的线程切换和DataResult剥离
     *
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<Response<DataResult<T>>, T> transResponseDataAndSchedule() {
        return upstream -> upstream.compose(RxUtil.transResponseData()).compose(RxUtil.<T>transSchedule());
    }


}
